package myself.study.network.tcp.examples.ex03.multiThread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
* @Name: FileUploadServerRunnable
* @Description: 文件上传服务多线程执行类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午10:39:41 
* @Version: V1.0
 */
public class FileUploadServerRunnable implements Runnable {
	
	private Socket socket ; 
	
	public FileUploadServerRunnable() {
	}

	public FileUploadServerRunnable(Socket socket) {
		this.socket = socket ;
	}

	@Override
	public void run() {
		try {
			//获取输入流对象，并包装成高效缓冲字符读取流
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
			//获取文件输出流对象，并包装成高效缓冲字符写入流
			String fileName = System.currentTimeMillis() + ".java" ;
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)) ;
			String line = null ;
			while((line = reader.readLine()) != null) { //阻塞
				//将客户端发送的文件上传到指定目录
				writer.write(line) ;
				writer.newLine() ;
				writer.flush() ;
			}
			//向客户端反馈上传状态结果
			BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())) ;
			String status = "上传成功!" ;
			writer2.write(status) ;
			writer2.newLine() ;
			writer2.flush() ;
			//释放资源
			writer.close() ;
			socket.close() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}

}
